import talib as ta

from . import BinanceKlineFactroy


def get_cumulative_amount(klines):  # 累积量
    cumulative_amount = 0
    for macd in klines['MACD'].values:
        cumulative_amount += abs(macd)
    return cumulative_amount


def get_price_difference(klines):  # 价差
    return abs(klines['close'].values[-1] - klines['open'].values[0])


def divergence(klines):  # 背离 -1底  1顶
    if klines['state'].values[-1] == 0:
        return 0
    now_klines_group = BinanceKlineFactroy.klines_group(klines, 0)
    now_cumulative_amount = get_cumulative_amount(now_klines_group)
    last_cumulative_amount = get_cumulative_amount(now_klines_group)
    now_price_difference = get_price_difference(now_klines_group)
    last_price_difference = get_price_difference(now_klines_group)
    if now_cumulative_amount == 0:
        var1 = 0
    else:
        var1 = last_cumulative_amount / now_cumulative_amount

    if now_price_difference == 0:
        var2 = 0
    else:
        var2 = now_price_difference / last_price_difference

    if var1 <= var2:
        if now_klines_group['state'].values[0] == -1:
            return -1
        elif now_klines_group['state'].values[0] == 1:
            return 1

    return 0


def MA(klines, matype):
    return float(ta.MA(klines['close'][-matype:].values, matype)[-1:])


def interval_to_second(interval: str):
    if interval == '1m':
        return 60
    elif interval == '3m':
        return 3 * 60
    elif interval == '5m':
        return 5 * 60
    elif interval == '15m':
        return 15 * 60
    elif interval == '30m':
        return 30 * 60
    elif interval == '1h':
        return 60 * 60
    elif interval == '2h':
        return 2 * 60 * 60
    elif interval == '4h':
        return 4 * 60 * 60
    elif interval == '6h':
        return 6 * 60 * 60
    elif interval == '8h':
        return 8 * 60 * 60
    elif interval == '12h':
        return 12 * 60 * 60
    elif interval == '1d':
        return 24 * 60 * 60
    elif interval == '3d':
        return 3 * 24 * 60 * 60
    elif interval == '1w':
        return 7 * 24 * 60 * 60
